import pandas as pd
from datetime import datetime
import os
from data_generator import DataGenerator
from recommendation_engine import RecommendationEngine


class RecommendationService:
    """推荐服务接口 - 展示层"""

    def __init__(self, data_dir="data"):
        # 初始化数据生成器
        self.data_generator = DataGenerator()

        # 初始化引擎为空
        self.engine = None

        # 初始化统计数据
        self.stats = {
            "total_users": 0,        # 总用户数
            "total_products": 0,     # 总产品数
            "total_interactions": 0, # 总交互数
            "last_init_time": None   # 上次初始化时间
        }

        # 设置数据目录
        self.data_dir = data_dir

        # 生成运行ID
        self.run_id = datetime.now().strftime("%Y%m%d_%H%M%S")

        # 确保数据目录存在
        os.makedirs(data_dir, exist_ok=True)


    def initialize(self, user_count=1000, product_count=500, interaction_count=20000, save_data=True):
        """初始化数据并构建推荐引擎"""
        # 打印开始生成模拟数据的时间
        print(f"[{datetime.now().strftime('%H:%M:%S')}] Generating mock data...")
        # 记录开始时间
        start_time = datetime.now()

        # 生成用户数据
        users = self.data_generator.generate_users(user_count)
        # 生成产品数据
        products = self.data_generator.generate_products(product_count)
        # 生成交互数据
        interactions = self.data_generator.generate_interactions(users, products, interaction_count)

        # 统计信息
        self.stats = {
            "total_users": len(users),  # 总用户数
            "total_products": len(products),  # 总产品数
            "total_interactions": len(interactions),  # 总交互数
            "last_init_time": datetime.now()  # 上次初始化时间
        }

        # 保存生成的数据
        if save_data:
            # 保存用户数据
            self.save_data(users, "users")
            # 保存产品数据
            self.save_data(products, "products")
            # 保存交互数据
            self.save_data(interactions, "interactions")

        # 打印开始构建推荐引擎的时间
        print(f"[{datetime.now().strftime('%H:%M:%S')}] Building recommendation engine...")
        # 构建推荐引擎
        self.engine = RecommendationEngine(users, products, interactions)

        # 计算初始化耗时
        elapsed = (datetime.now() - start_time).total_seconds()
        # 打印系统就绪信息和初始化耗时
        print(f"[{datetime.now().strftime('%H:%M:%S')}] System ready! Initialization took {elapsed:.2f} seconds")


    def save_data(self, df, data_type):
        """保存数据到CSV文件"""
        filename = f"{self.run_id}_{data_type}.csv"
        filepath = os.path.join(self.data_dir, filename)
        df.to_csv(filepath, index=False)
        print(f"  - Saved {data_type} data to {filepath} ({len(df)} records)")

    def save_recommendations(self, df, user_id):
        """保存推荐结果到CSV文件"""
        filename = f"{self.run_id}_recommendations_{user_id}.csv"
        filepath = os.path.join(self.data_dir, filename)
        df.to_csv(filepath, index=False)
        return filepath

    def get_system_stats(self):
        """获取系统统计信息"""
        return self.stats

    def get_user_profile(self, user_id):
        """获取用户画像详情"""
        # 检查引擎是否初始化
        if not self.engine:
            # 如果没有初始化，抛出异常
            raise Exception("System not initialized. Call initialize() first.")

        # 检查用户ID是否存在于用户画像中
        if user_id not in self.engine.user_profiles:
            # 如果用户ID不存在，返回错误信息
            return {"status": "error", "message": "User not found"}

        # 获取用户画像
        profile = self.engine.user_profiles[user_id]
        return {
            "status": "success",
            "user_id": user_id,
            # 基础画像信息
            "base_profile": profile["base"],
            # 行为画像信息
            "behavior_profile": profile["interaction_stats"]
        }


    def get_recommendations(self, user_id, top_n=10, include_profile=False, save_results=True):
        """获取推荐结果"""
        # 检查系统是否初始化
        if not self.engine:
            raise Exception("System not initialized. Call initialize() first.")

        # 打印开始生成推荐的时间
        print(f"\n[{datetime.now().strftime('%H:%M:%S')}] Generating recommendations for user {user_id}...")
        start_time = datetime.now()

        # 生成推荐结果
        recs_df = self.engine.generate_recommendations(user_id, top_n)

        # 计算生成推荐结果的时间
        elapsed_ms = (datetime.now() - start_time).total_seconds() * 1000
        print(f"[{datetime.now().strftime('%H:%M:%S')}] Generated {len(recs_df)} recommendations in {elapsed_ms:.2f}ms")

        # 保存推荐结果
        if save_results:
            # 保存推荐结果到指定路径
            saved_path = self.save_recommendations(recs_df, user_id)
            print(f"  - Saved recommendations to {saved_path}")

        # 构建推荐结果字典
        result = {
            "user_id": user_id,
            "recommendations": recs_df.to_dict(orient="records"),
            "generation_time_ms": elapsed_ms
        }

        # 如果包含用户信息，则添加用户信息到结果字典
        if include_profile:
            result["user_profile"] = self.get_user_profile(user_id)

        return result


    def batch_recommendations(self, user_ids, top_n=5, save_results=True):
        """批量生成推荐"""
        results = []
        for user_id in user_ids:
            try:
                # 获取单个用户的推荐结果
                res = self.get_recommendations(user_id, top_n, save_results=save_results)
                results.append(res)
            except Exception as e:
                # 捕获异常并记录错误信息
                results.append({
                    "user_id": user_id,
                    "error": str(e)
                })
        return results


